package jp.co.cos.ittrick.channel.controller.client;

import java.util.ArrayList;
import java.util.List;

import jp.co.cos.ittrick.channel.model.ChapterModel;
import jp.co.cos.ittrick.channel.service.ChapterService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Text;

public class UpdateChapterController extends Controller {

    private ChapterService chapterService;

    public UpdateChapterController() {
        chapterService = new ChapterService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String chapter = asString("chapter");
        String name = asString("name");
        String index = asString("index");
        String content = asString("content");
        String keyWords = asString("keyWord");
        String description = asString("description");

        List<String> keyWordList = getStringList(keyWords);

        // Modelの設定
        ChapterModel model = chapterService.getChapterByKey(Integer.valueOf(chapter));
        if(model != null) {
            model.setName(name);
            model.setIndex(Integer.valueOf(index));
            model.setKeyWordList(keyWordList);
            model.setDescription(description);
            model.setContent(new Text(content));

            // Insert
            chapterService.update(model);
        }

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.getWriter().println("0");
        response.flushBuffer();

        return null;
    }

    private List<String> getStringList(String texts) {

        List<String> stringList = new ArrayList<String>();
        if(texts != null && texts != "" && !texts.equals("null")) {
            String[] amznWdgtAsinsTmp = texts.split(",");
            for(String txt: amznWdgtAsinsTmp) {
                if(!txt.isEmpty()) {
                    stringList.add(txt);
                }
            }
        }
        return stringList;
    }
}
